<template>
  <wd-tabbar v-model="tabbar" :safeAreaInsetBottom="true" :fixed="true" @change="switchTab">
    <wd-tabbar-item
      v-for="(item, index) in tabBarList"
      :key="index"
      :title="item.text"
      :icon="item.icon"
      :bordered="false"
      :name="item.name"
      :value="item.name === 'shopcart' ? shopcartLength : 0"
    ></wd-tabbar-item>
  </wd-tabbar>
</template>

<script setup>
import { useShopcartStore, useProfileStore } from '@/store'
// 使用购物车和用户信息的状态管理
const shopcartStore = useShopcartStore()
const { mpLoginParams } = useProfileStore()

// 创建响应式引用
const shopcartLength = ref(shopcartStore.shopcartLength)
const tabbar = ref('index')

// 监视购物车长度的变化
watch(
  () => shopcartStore.shopcartLength,
  (newLength) => {
    shopcartLength.value = newLength
  },
)

const storeTabBarList = [
  {
    iconPath: 'static/tabbar/home.png',
    selectedIconPath: 'static/tabbar/homeHL.png',
    pagePath: '/pages/index/index',
    name: 'index',
    icon: 'home',
    text: '首页',
  },
  {
    iconPath: 'static/tabbar/category.png',
    selectedIconPath: 'static/tabbar/categoryHL.png',
    pagePath: '/pages/category/category',
    name: 'category',
    icon: 'app',
    text: '分类',
  },
  {
    iconPath: 'static/tabbar/shopcart.png',
    selectedIconPath: 'static/tabbar/shopcartHL.png',
    pagePath: '/pages/shopcart/shopcart',
    name: 'shopcart',
    icon: 'cart',
    text: '购物车',
  },
  {
    iconPath: 'static/tabbar/profile.png',
    selectedIconPath: 'static/tabbar/profileHL.png',
    pagePath: '/pages/profile/profile',
    name: 'profile',
    icon: 'user',
    text: '我的',
  },
]

const driverTabBarList = [
  {
    iconPath: 'static/tabbar/home.png',
    selectedIconPath: 'static/tabbar/homeHL.png',
    pagePath: '/pages/index-driver/index-driver',
    name: 'index-driver',
    icon: 'home',
    text: '首页',
  },
  {
    iconPath: 'static/tabbar/profile.png',
    selectedIconPath: 'static/tabbar/profileHL.png',
    pagePath: '/pages/profile-driver/profile-driver',
    name: 'profile-driver',
    icon: 'user',
    text: '我的',
  },
]

const tabBarList = ref([])

const switchTab = ({ value }) => {
  const targetRoute = tabBarList.value.find((item) => item.name === value)
  uni.switchTab({
    url: targetRoute.pagePath,
  })
}

const setTabBarList = () => {
  if (mpLoginParams.isDriver) {
    tabBarList.value = driverTabBarList
  } else {
    tabBarList.value = storeTabBarList
  }
}

const updateSelectedTab = () => {
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  const targetRoute = tabBarList.value.find((item) => item.pagePath.includes(page.route))
  if (targetRoute) {
    tabbar.value = targetRoute.name
  }
}

onShow(() => {
  setTabBarList()
  updateSelectedTab()
})
</script>

<style lang="scss" scoped></style>
